//
//  SerialGroupView.m
//  XPhoto
//
//  Created by baboy on 2019/7/8.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "SerialGroupView.h"
#import "Group.h"
#import "Post.h"
#import <BKKit/UIButton+x.h>
#import "UIButton+tag.h"

#define TITLE_FONT [UIFont systemFontOfSize:12]
#define VIEW_MARGIN 10
#define BUTTON_MAX_WIDTH 320
#define TAG_BTN_BG_COLOR [UIColor colorWithWhite:1.0f alpha:1.0f]


@interface SerialGroupView()
@property(nonatomic, strong) IBOutlet UIScrollView *scrollView;
@property(nonatomic, strong) IBOutlet UIButton *titleButton;
@property(nonatomic, strong) NSMutableArray<UIButton *> *itemButtons;
@property(nonatomic, strong) IBOutlet UIView *lineView;
@property(nonatomic, strong) IBOutlet UIButton *loadingButton;

- (IBAction)clickTitleButton:(id)button;
@end
@implementation SerialGroupView
- (void)awakeFromNib{
    [super awakeFromNib];
//    self.titleButton.backgroundColor = TAG_BTN_BG_COLOR;
//    self.titleButton.layer.borderColor = [THEME_TAG_BTN_BORDER_COLOR CGColor];
//    self.titleButton.layer.borderWidth = 1;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    DLOG(@"SerialGroupView******");
}
- (void)setTitle:(NSString *)title{
    _title = title;
    [self.titleButton setTitle:title forState:UIControlStateNormal];
//    [self sizeToFit];
//    [self.titleButton sizeToFitWidth];
//    self.titleButton.imageLocation = UIButtonImageLocationRight;
    
//    CGRect titleButtonFrame = self.titleButton.frame;
//    CGSize titleSize = [title boundingRectWithSize:CGSizeMake(self.bounds.size.width, CGFLOAT_MAX)
//                                           options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleButton.titleLabel.font} context:nil].size;
//
//    titleButtonFrame.size.width = titleButtonFrame.size.height + 10 + 3 + titleSize.width+50;
//    titleButtonFrame.origin.x = (self.bounds.size.width - titleButtonFrame.size.width)/2;
//    self.titleButton.frame = titleButtonFrame;
//
//    self.titleButton.imageEdgeInsets = UIEdgeInsetsMake(0, self.titleButton.titleLabel.frame.size.width + 3, 0, -self.titleButton.titleLabel.frame.size.width - 3);
//    self.titleButton.titleEdgeInsets = UIEdgeInsetsMake(0, -self.titleButton.imageView.frame.size.width, 0, self.titleButton.imageView.frame.size.width);
    
}
- (UIView *)createItemViewWithTitle:(NSString *)title subtitle:(NSString *)subtitle frame:(CGRect)itemFrame{
    
    UIButton *titleButton = [UIButton buttonWithTag:title image:nil];
    
    CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: THEME_TAG_BTN_TITLE_FONT}];
    CGSize subtitleSize = subtitle ? [subtitle sizeWithAttributes:@{NSFontAttributeName: THEME_TAG_BTN_TITLE_FONT}] : CGSizeZero;
    titleSize.width = MIN(titleSize.width+titleButton.contentEdgeInsets.left+ titleButton.contentEdgeInsets.right, BUTTON_MAX_WIDTH);
    subtitleSize.width += 10;
    
    itemFrame.size.width = MAX(titleSize.width, subtitleSize.width)+20;
    UIView *itemView = [[UIView alloc] initWithFrame:itemFrame];
    
    CGRect titleFrame = CGRectMake((itemFrame.size.width-titleSize.width)/2, VIEW_MARGIN, titleSize.width, TAG_BUTTON_HEIGHT);
    
    
//    titleFrame.size = titleButton.frame.size;
    titleButton.frame = titleFrame;
    
    [titleButton addTarget:self action:@selector(clickSerialItem:) forControlEvents:UIControlEventTouchUpInside];
    [titleButton setTitle:title forState:UIControlStateNormal];
    titleButton.frame = titleFrame;
    [itemView addSubview: titleButton];
    if (_showSubtitle) {
        CGRect subtitleFrame = CGRectMake((itemFrame.size.width-subtitleSize.width)/2, titleFrame.origin.y+titleFrame.size.height+5, subtitleSize.width, TAG_BUTTON_HEIGHT);
        UILabel *subtitleLabel = [[UILabel alloc] initWithFrame:subtitleFrame];
        subtitleLabel.textColor = THEME_TEXT_COMMENT_COLOR;
        subtitleLabel.font = THEME_TAG_BTN_TITLE_FONT;
        subtitleLabel.text = subtitle;
        subtitleLabel.textAlignment = NSTextAlignmentCenter;
        [itemView addSubview: subtitleLabel];
    }
    return itemView;
}
- (void)layoutLineView{
    if (!self.itemButtons || self.itemButtons.count < 2) {
        self.lineView.hidden = YES;
        return;
    }
    UIButton *firstButton = self.itemButtons.firstObject;
    UIButton *lastButton = self.itemButtons.lastObject;
    CGPoint s = [firstButton convertPoint:firstButton.bounds.origin toView:self.scrollView];
    CGPoint e = [lastButton convertPoint:firstButton.bounds.origin toView:self.scrollView];
    CGRect lineFrame = CGRectMake(s.x, s.y+firstButton.bounds.size.height/2-1, e.x-s.x, 1);
    self.lineView.frame = lineFrame;
    self.lineView.hidden = NO;
}
- (void)setItems:(NSMutableArray *)items{
    _items = items;
    if (self.itemButtons && self.itemButtons.count > 0) {
        for (UIView *v in self.itemButtons) {
            [v.superview removeFromSuperview];
        }
        self.loadingButton = nil;
    }
    
    CGRect itemFrame = CGRectMake(0, 0, 0, self.scrollView.bounds.size.height);
    self.itemButtons = [NSMutableArray array];
    CGSize contentSize = self.scrollView.bounds.size;
    for (NSInteger i = 0; i<items.count; i++) {
        Group *grp = [items objectAtIndex:i];
        UIView *itemView = [self createItemViewWithTitle:grp.title subtitle:grp.subtitle frame:itemFrame];
        [self.scrollView addSubview: itemView];
        UIButton * titleButton = itemView.subviews.firstObject;
        titleButton.tag = i;
        [self.itemButtons addObject:titleButton];
        itemFrame = itemView.frame;
        itemFrame.origin.x += itemFrame.size.width;
        contentSize.width = itemFrame.origin.x;
    }
    [self setSelectedIndex:self.selectedIndex];
    
    [self layoutLineView];
    
    self.scrollView.contentSize = contentSize;
    self.selectedIndex = _selectedIndex;
    self.loadMore = _loadMore;
}
- (void)setLoadMore:(BOOL)loadMore{
    _loadMore = loadMore;
    if (!loadMore && self.loadingButton) {
        [self.loadingButton removeFromSuperview];
        [self.itemButtons removeObject:self.loadingButton];
        self.loadingButton = nil;
        [self layoutLineView];
    }
    if(loadMore && !self.loadingButton){
        CGRect itemFrame = self.itemButtons.lastObject.superview.frame;
        itemFrame.origin.x += itemFrame.size.width;
        UIView *itemView = [self createItemViewWithTitle:@"  ···  " subtitle:nil frame:itemFrame];
        self.loadingButton = itemView.subviews.firstObject;
        [self.scrollView addSubview:itemView];
        [self.itemButtons addObject:self.loadingButton];
        [self layoutLineView];
    }
}
- (void)setSelectedIndex:(NSInteger)selectedIndex{
    if(selectedIndex >= self.itemButtons.count){
        return;
    }
    UIButton *previousButton = [self.itemButtons objectAtIndex:_selectedIndex];
    UIButton *currentButton = [self.itemButtons objectAtIndex:selectedIndex];
    previousButton.backgroundColor = TAG_BTN_BG_COLOR;
    previousButton.selected = NO;
    
    currentButton.backgroundColor = THEME_TAG_BTN_SELECTED_BG_COLOR;
    currentButton.selected = YES;
    
    _selectedIndex = selectedIndex;
}
- (void)clickSerialItem:(UIButton*)button{
    if (button == self.loadingButton) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didClickedSerialGroupLoadingMoreButton:)]) {
            [self.delegate didClickedSerialGroupLoadingMoreButton:button];
        }
        return;
    }
    self.selectedIndex = button.tag;
    if(self.delegate && [self.delegate respondsToSelector:@selector(didClickedSerialGroupItemAtIndex:)]){
        [self.delegate didClickedSerialGroupItemAtIndex:button.tag];
    }
    //自动滚动至中间位置
    CGRect itemFrame = button.superview.frame;
    CGFloat rightMargin = self.scrollView.bounds.size.width - ( itemFrame.origin.x - self.scrollView.contentOffset.x + itemFrame.size.width);
    CGFloat leftMargin = itemFrame.origin.x - self.scrollView.contentOffset.x;
    if (leftMargin < 50 || rightMargin < 50) {
        CGFloat itemCenterX = itemFrame.origin.x - self.scrollView.contentOffset.x + itemFrame.size.width/2;
        CGFloat offsetX = self.scrollView.bounds.size.width/2 - itemCenterX;
        CGPoint offset = CGPointMake(self.scrollView.contentOffset.x - offsetX, 0);
        offset.x = MAX(offset.x, 0);
        offset.x = MIN(offset.x, self.scrollView.contentSize.width - self.scrollView.bounds.size.width);
        offset.x = MAX(offset.x, 0);
        [self.scrollView setContentOffset:offset animated:YES];
    }
}
- (IBAction)clickTitleButton:(id)button{
    if(self.delegate && [self.delegate respondsToSelector:@selector(didClickedSerialGroupTitleButton:)]){
        [self.delegate didClickedSerialGroupTitleButton:button];
    }
}
- (CGFloat)height{
    CGFloat h = self.titleButton.frame.origin.y + self.titleButton.frame.size.height + VIEW_MARGIN + TAG_BUTTON_HEIGHT + VIEW_MARGIN;
    if (self.showSubtitle) {
        h += 5 + TAG_BUTTON_HEIGHT;
    }
    return h;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
@end
